package com.young.ysepay.controllers;


import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.young.ysepay.mq.YsReturnMQConfig;
import com.young.ysepay.service.YsService;
import com.young.ysepay.utils.JSONUtils;
import com.young.ysepay.utils.ReturnUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;



/**
 * @anthor wenguoqiang
 * @date: 2019/04/14 10:57
 * @company 够样
 * @des
 **/
@RestController
@RequestMapping("/ysBaseService")
public class YsController {

    private static Logger log = LoggerFactory.getLogger(YsController.class);

    @Autowired
    private YsService ysService;

    @Autowired(required = false)
    private Producer producer;
    /**
     * @Author zhaopengjun
     * @Description //银盛分账查询接口
     * @Date 10:19 2019/5/14
     * @Param
     * @return
     **/
    @RequestMapping(value = { "/splitRequestReceipt" })
    public String splitRequestReceipt(@RequestParam Map<String,Object> paraMap){
        System.out.println("----------- 请求银盛分账查询---------------");
        String responseStr = "";
        String bizContent = (String) paraMap.get("biz_content");
        Map<String, Object> returnMap = null;
        try {
            returnMap =  ysService.splitRequestReceipt(bizContent);
        }catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        }finally {
            responseStr = JSONUtils.objectToJson(returnMap);
        }
        return ReturnUtils.appendResultStr(log,responseStr,"splitRequestReceipt");
    }

    /**
     * @Author zhaopengjun
     * @Description // 银盛分账登记请求（一清）
     * @Date 18:07 2019/5/14
     * @Param
     * @return
     **/
    @RequestMapping(value = { "/splitReceipt" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    public String splitReceipt(@RequestParam Map<String,Object> mapParams){

        System.out.println("----------- 请求银盛分账---------------");


        String responseStr = "";
        Map<String, Object> returnMap = null;
        try {
            returnMap =  ysService.splitReceipt(mapParams);
        }catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            responseStr = JSONUtils.objectToJson(returnMap);
        }
        return ReturnUtils.appendResultStr(log,responseStr,"splitReceipt");
    }

    /**
     * @Author zhaopengjun
     * @Description // 银盛实时提现（二清）
     * @Date 15:03 2019/5/20
     * @Param
     * @return
     **/
    @RequestMapping(value = { "/withdrawal" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    public String withdrawal(@RequestParam Map<String,Object> mapParams){
        System.out.println("----------- 银盛实时提现---------------");

        String responseStr = "";
        Map<String, Object> returnMap = null;
        try {
            returnMap =  ysService.withdrawal(mapParams);
        }catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            responseStr = JSONUtils.objectToJson(returnMap);
        }
        return ReturnUtils.appendResultStr(log,responseStr,"withdrawal");
    }

    /**
     * @Author zhaopengjun
     * @Description //银盛分账异步回执接口（一清）
     * @Date 15:12 2019/5/22
     * @Param [returnString]
     * @return java.lang.String
     **/
    @PostMapping("/ysAsynchronousReturn")
    public String ysAsynchronousReturn(@RequestParam String returnString) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        System.out.println("======= 银盛异步回执请求参数！！=========");
        resultMap = (Map) JSON.parse(returnString);
        String infoJson = (String) resultMap.get("ysepay_single_division_online_accept_response");
        Object temp = resultMap.get("sign");
        String sign = temp != null ? temp.toString() : null;
        Object temp1 = resultMap.get("charset");
        String charset = temp1 != null ? temp1.toString() : null;
        SendResult result = null;
        if (!sign.isEmpty()&& !infoJson.isEmpty()) {
            boolean b = false;
            try {
                //校验签名是否正确
                b = ysService.verifyJsonSign(sign, infoJson.toString(), charset);
                if(b){
                    Message message = new Message(YsReturnMQConfig.SETTLETOPIC, YsReturnMQConfig.YSSPLITRECEIPT_TAG, infoJson.getBytes());
                    result = producer.send(message);
                    assert result != null;
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("验证签名失败，请检查银盛公钥证书文件是否存在");
            }
        }
        return null;
    }
    /**
     * @Author zhaopengjun
     * @Description //银盛实时提现异步返回
     * @Date 16:55 2019/5/21
     * @Param [returns]
     * @return java.lang.String
     **/
    @RequestMapping(value = { "/ysAsyncWithdrawal" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    public String ysAsyncWithdrawal(@RequestParam String returns){
        System.out.println("-------------------------银盛实时提现异步返回-----------------------------");
        Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap = (Map) JSON.parse("returns");

        Object temp = resultMap.get("ysepay_merchant_withdraw_quick_accept");
        String obj = temp != null ? temp.toString() : null;
        String sign = (String) resultMap.get("sign");
        Object temp1 = resultMap.get("charset");
        String charset = temp1 != null ? temp1.toString() : null;
        SendResult result = null;
        if (!sign.isEmpty()&& !obj.isEmpty()) {
            boolean b = false;
            try {
                //校验签名是否正确
                b = ysService.verifyJsonSign(sign, obj.toString(), charset);
                if(b){
                    Message message = new Message(YsReturnMQConfig.SETTLETOPIC, YsReturnMQConfig.YSWITHDRAWALRECEIPT_TAG, obj.getBytes());
                    result = producer.send(message);
                    assert result != null;
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("验证签名失败，请检查银盛公钥证书文件是否存在");
            }
        }
        return null;
    }

    /**
     * @Author zhaopengjun
     * @Description //银盛支付异步回执
     * @Date 16:56 2019/5/21
     * @Param
     * @return
     **/
    @RequestMapping(value = { "/ysAsyncPay" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    public String ysAsyncPay(@RequestParam String returns) {
        System.out.println("-------------------------银盛实时提现异步返回-----------------------------");
        Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap = (Map) JSON.parse("returns");

        Object temp = resultMap.get("ysepay_online_sdkpay");
        String obj = temp != null ? temp.toString() : null;
        String sign = (String) resultMap.get("sign");
        Object temp1 = resultMap.get("charset");
        String charset = temp1 != null ? temp1.toString() : null;
        SendResult result = null;
        if (!sign.isEmpty() && !obj.isEmpty()) {
            boolean b = false;
            try {
                //校验签名是否正确
                b = ysService.verifyJsonSign(sign, obj, charset);
                if (b) {
                    Message message = new Message(YsReturnMQConfig.PAYTOPIC, YsReturnMQConfig.PAY_TAG, obj.getBytes());
                    result = producer.send(message);
                    assert result != null;
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("验证签名失败，请检查银盛公钥证书文件是否存在");
            }
        }
        return null;
    }

    /**
     * @Author zhaopengjun
     * @Description // 银盛支付接口（H5）
     * @Date 17:47 2019/5/22
     * @Param
     * @return
     **/
    @RequestMapping(value = { "/ysPay" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    public String ysPay(@RequestParam Map<String,Object> paramMap){
        System.out.println("----------- 银盛支付---------------");

        String responseStr = "";
        Map<String, Object> returnMap = null;
        try {
            returnMap =  ysService.ysPay(paramMap);
        }catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            responseStr = JSONUtils.objectToJson(returnMap);
        }
        return ReturnUtils.appendResultStr(log,responseStr,"ysPay");
    }

    /**
     * @Author zhaopengjun
     * @Description //银盛商户余额查询（一清提现）
     * @Date 15:48 2019/5/23
     * @Param
     * @return
     **/
    @RequestMapping(value = { "/balanceQuery" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    public String balanceQuery(@RequestParam Map<String,Object> paramMap){
        System.out.println("----------- 银盛商户余额查询---------------");

        String responseStr = "";
        Map<String, Object> returnMap = null;
        try {
            returnMap =  ysService.ysBalanceQuery(paramMap);
        }catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            responseStr = JSONUtils.objectToJson(returnMap);
        }
        return ReturnUtils.appendResultStr(log,responseStr,"balanceQuery");
    }

    /**
     * @Author zhaopengjun
     * @Description //银盛单笔代付接口（非一清待打款接口）
     * @Date 9:58 2019/5/24
     * @Param
     * @return
     **/
    @RequestMapping(value = { "/transferAccounts" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    public String transferAccounts(@RequestParam Map<String,Object> mapParams){
        System.out.println("----------- 银盛非一清待打款接口---------------");

        Map<String, Object> returnMap = null;
        String responseStr = "";
        try {
            returnMap = ysService.transferAccounts(mapParams);
        } catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            responseStr = JSONUtils.objectToJson(returnMap);
        }
        return ReturnUtils.appendResultStr(log,responseStr,"transferAccounts");
    }

    /**
     * @Author zhaopengjun
     * @Description //盛非一清待打款接口异步返回
     * @Date 11:58 2019/5/24
     * @Param
     * @return
     **/
    @RequestMapping(value = { "/ysAsyncBalanceQuery" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    public String ysAsyncBalanceQuery(@RequestParam String returns) {
        System.out.println("-------------------------银盛非一清待打款接口异步返回-----------------------------");
        Map<String, Object> resultMap = new HashMap<String, Object>();

        //Boolean b = ysBaseService.ysAsyncBalanceQuery(returns);
        resultMap = (Map) JSON.parse("returns");

        Object temp = resultMap.get("ysepay_df_single_quick_accept");
        String obj = temp != null ? temp.toString() : null;
        String sign = (String) resultMap.get("sign");
        Object temp1 = resultMap.get("charset");
        String charset = temp1 != null ? temp1.toString() : null;
        SendResult result = null;
        if (!sign.isEmpty() && !obj.isEmpty()) {
            boolean b = false;
            try {
                //校验签名是否正确
                b = ysService.verifyJsonSign(sign, obj, charset);
                if (b) {
                    Message message = new Message(YsReturnMQConfig.SETTLETOPIC, YsReturnMQConfig.YSPAYMENT_TAG, obj.getBytes());
                    result = producer.send(message);
                    assert result != null;
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("验证签名失败，请检查银盛公钥证书文件是否存在");
            }
        }
        return null;

    }


}
